package org.vincen.helloworld.memcached;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import net.spy.memcached.AddrUtil;
import net.spy.memcached.MemcachedClient;

public class TestMem {

	public static void main(String[] args) {
		// 同步
//		MemcachedClient c = null;
//		try {
//			c = new MemcachedClient(new InetSocketAddress("192.168.1.104", 11211));
//		} catch (IOException e) {
//			e.getMessage();
//		}
//		// Store a value (async) for one hour
//		c.set("someKey", 3600, new String("vincen"));
//		// Retrieve a value (synchronously).
//		Object myObject = c.get("someKey");
//		System.out.println(myObject);
		
		// 异步
		//获取一个连接到几个服务端的memcached的客户端
		MemcachedClient c = null;
		try {
			c = new MemcachedClient(AddrUtil.getAddresses("192.168.1.128:11211"));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		//获取值，如果在5秒内没有返回值，将取消
		Object myObj = null;
		Future<Object> f = c.asyncGet("someKey");
		try{
			myObj = f.get(5,TimeUnit.SECONDS);
			System.out.println(myObj);
		}catch(TimeoutException e){
			f.cancel(false);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}
}
